package com.kt.delivery.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "weixin")
@Data
@Slf4j
public class WechatUtil {


    private  String appid;

    private  String secret;

    @Autowired
    private static RestTemplate restTemplate;


    /**
     * 获取openid用户唯一标识
     * @param code
     * @return
     */
    public String getSessionKeyOpenid(String code) throws IOException {

        String weixinUrl = "https://api.weixin.qq.com/sns/jscode2session";


        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(weixinUrl+"?"+"appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code");

        //创建请求对象 发送get请求读取调用微信接口获取openid用户唯一标识
        HttpGet httpGet = new HttpGet(String.valueOf(stringBuilder));


        CloseableHttpResponse response = httpClient.execute(httpGet);

        // 结果
        HttpEntity entity = response.getEntity();

        String body = EntityUtils.toString(entity);

        log.info("结果"+body);


        log.info("微信接口调用地址:"+stringBuilder.toString());



        //关闭资源
        response.close();
        httpClient.close();

        return body;
    }















}
